<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/5
 * Time: 12:39
 */

namespace Order\Controller;


use Think\Controller;

/**
 * 订单管理
 * Class IndexController
 * @package Order\Controller
 */
class IndexController extends Controller
{
    //引入订单列表模板页
    public function index(){
        $this->display();
    }
    //列表页提供数据接口
    public function getOrderList(){
        $user_token = session('NOW_USER_TOKEN');//获取用户信息
        $user_info = M('userdetail')->where(['token'=>$user_token])->find();
        $group_id = M('group_table')->where(['userid'=>$user_info['userid']])->getField('id');
        //获取订单信息
        $orders = M('client_book')->where(['fake_id'=>'B888'.$group_id])->order('id desc')->select();
        //构建数据
        $json_string = [];
        foreach ($orders as $item){
            if($item['ordstatus'] == '0'){
                $item['ordstatus'] = '关闭';
            }elseif ($item['ordstatus'] == '1'){
                $item['ordstatus'] = '待付款';
            }elseif ($item['ordstatus'] == '2'){
                $item['ordstatus'] = '已付款（进行中）';
            }elseif ($item['ordstatus'] == '3'){
                $item['ordstatus'] = '已完成';
            }
            $json_string['data'][] = [
                $item['id'],
                $item['ordid'],
                date('Y-m-d H:i:s',$item['starttime']),
                $item['linkman'],
                $item['linkphone'],
                $item['price'] * $item['amount'],
                $item['server_type'],
                date('Y-m-d H:i:s',$item['servertime']),
                $item['ordstatus'],
            ];
        }
        $this->ajaxReturn($json_string);
    }

    /**
     * 获取指定订单详情
     */
    public function getOrderDetail($id){
        $order_info = M('client_book')->where(['id'=>$id])->find();
        if($order_info['ordstatus'] == '0'){
            $order_info['ordstatus'] = '关闭';
        }elseif ($order_info['ordstatus'] == '1'){
            $order_info['ordstatus'] = '待付款';
        }elseif ($order_info['ordstatus'] == '2'){
            $order_info['ordstatus'] = '已付款（进行中）';
        }elseif ($order_info['ordstatus'] == '3'){
            $order_info['ordstatus'] = '已完成';
        }
        //获取下订单用户信息
        $order_user = M('userdetail')->where(['userid'=>$order_info['user_id']])->find();
        //获取被服务人信息
        $server_people = M('be_servepeople')->where(['id'=>$order_info['beserve_id']])->find();
        //获取套餐信息
        $package = M('package')->where(['id'=>$order_info['package_id']])->find();
        $this->assign('package',$package);
        $this->assign('order_info',$order_info);
        $this->assign('order_user',$order_user);
        $this->assign('server_people',$server_people);
        $this->display('detail');
    }

    /**
     * ajax修改订单部分信息
     * linkman、linkphone、price
     */
    public function ajaxUpdateOrder(){
        $id = I('id');
        $name = I('name');
        $phone = I('phone');
//        $tatol = I('price');
        //先验证该用户的合法性
        $fake_id = M('client_book')->where(['id'=>$id])->getField('fake_id');
        $user_token = session('NOW_USER_TOKEN');//获取用户信息
        $user_info = M('userdetail')->where(['token'=>$user_token])->find();
        $group_id = M('group_table')->where(['userid'=>$user_info['userid']])->getField('id');
        if($fake_id != 'B888'.$group_id){
            $this->ajaxReturn(['status'=>'0']);exit;
        }
        //名字字符串不能太短也不能太长
        if(strlen($name) >= 2 && strlen($name) < 10){
            $result = M('client_book')->where(['id'=>$id])->setField(['linkman'=>I('name')]) ? ['status'=>'1','name'=>I('name')] : ['status'=>'0'];
        }elseif($phone){
            //验证手机输入
            if(!is_numeric($phone) || !preg_match('/^1[34578]\d{9}$/',$phone)){
                $this->ajaxReturn(['status'=>'0']);exit;
            }
            $result = M('client_book')->where(['id'=>$id])->setField(['linkphone'=>I('phone')]) ? ['status'=>'1','phone'=>I('phone')] : ['status'=>'0'];
        }
//        elseif($tatol){
//            //验证价格输入
//            if(!is_numeric($tatol)){
//                $this->ajaxReturn(['status'=>'0']);exit;
//            }
//            $amount = M('client_book')->where(['id'=>$id])->getField('amount');
//            $price = round($tatol/$amount,2);
//            $result = M('client_book')->where(['id'=>$id])->setField(['price'=>$price]) ? ['status'=>'1','price'=>$price * $amount] : ['status'=>'0'];
//        }
        else{
            $result = ['status'=>'0'];
        }
        $this->ajaxReturn($result);
    }

    /**
     * 导出订单信息
     */
    public function exportOrderList() {
        $data = M('Userdetail')->select();   //查出数据
        $name = 'order' . date('Ymdhis',time());    //生成的Excel文件文件名
        $res = $this->_push($data,$name);
    }
    /* 导出excel函数*/
    private function _push($data,$name='Excel'){
        vendor('PHPExcel.PHPExcel');
        error_reporting(E_ALL);
        date_default_timezone_set('Europe/London');
        $objPHPExcel = new \PHPExcel();
        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("欧啦网")
            ->setLastModifiedBy("欧啦网")
            ->setTitle("数据EXCEL导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("订单信息")
            ->setKeywords("excel")
            ->setCategory("result file");
        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
        foreach($data as $k => $v){
            $num=$k+1;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，uid是你查出数组的键值，下面以此类推
                ->setCellValue('A'.$num, $v['userid'])
                ->setCellValue('B'.$num, $v['username'])
                ->setCellValue('C'.$num, $v['token']);
            }
        $objPHPExcel->getActiveSheet()->setTitle('User');
        $objPHPExcel->setActiveSheetIndex(0);
        ob_end_clean();//
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$name.'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
}